package cn.msqweb.filter;

import cn.msqweb.constant.AuthConstants;
import cn.msqweb.model.SecurityUser;
import cn.msqweb.util.JwtJson;
import com.alibaba.fastjson.JSONObject;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.util.Set;
import java.util.stream.Collectors;
@Configuration
public class  TokenTeansLationFilter extends OncePerRequestFilter {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     * token 转换过滤器
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String authConstants = request.getHeader(AuthConstants.AUTHORIZATION);
        if (StringUtils.hasText(authConstants)){
            String jwt_token = authConstants.replaceFirst(AuthConstants.BEARER, "");
            if (StringUtils.hasText(jwt_token) && JwtJson.verifyJWT(jwt_token.replaceAll("\"",""))){
                //从redis中取用户信息
//                String SecurityUserJsonStr = stringRedisTemplate.opsForValue().get(AuthConstants.LOGIN_TOKEN_PREFIX + token);

                String SecurityUserJsonStr = JwtJson.parseJWT(jwt_token);
                if (StringUtils.hasText(SecurityUserJsonStr)){
                    //从redis中拿到的用户信息装换成 SecurityUser 对象
                    SecurityUser securityUser = JSONObject.parseObject(SecurityUserJsonStr, SecurityUser.class);
                    //生成 Security 需要的权限集合
                    Set<SimpleGrantedAuthority> collect = securityUser.getPerms().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toSet());
                    //放入 Security 容器中
                    UsernamePasswordAuthenticationToken authenticationToken =new UsernamePasswordAuthenticationToken(securityUser,null,collect);

                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);

                    filterChain.doFilter(request,response);
                }
            }
        }



    }
}
